$NG.AllReady(function (page, { useValuesChange, useUpdateRow, useUpdateRows }) {
    // 获取控件
    const form = $NG.getCmpApi("p_form_equipment_list_split");
    const grid = $NG.getCmpApi("p_form_equipment_split_d");
    const grid2 = $NG.getCmpApi("p_form_equipment_split_dd");
  
    const dataMaps_key = {};
  
    // 监听表头 `u_split_rate` 变化
    useValuesChange(({ args }) => {
      console.log("useValuesChange is ready", args[0]);
  
      const u_split_rate = form.getItem("u_split_rate").getValue();
      const data = grid.getData().map((item) => ({ ...item, u_split_rate }));
  
      data.forEach(sum);
  
      grid.clearRows().then(() => grid.addRows(data));
      caculatedgrid();
    }, "p_form_equipment_list_split.u_split_rate");
  
    // 隐藏 grid1 按钮
    const gridToolbar = $NG.getCmpApi("toolbar_p_form_equipment_split_d");
    gridToolbar.getItem("imp").setProps({ children: "引用设备清单明细" });
    ["attachment", "addrow"].forEach((btn) => gridToolbar.hideButton(btn));
  
    useUpdateRow(caculatedgrid, "p_form_equipment_split_d");
  
    useUpdateRows(({ args }) => {
      console.log(`表格新增监听`, args);
      setSpiltAmt();
      // caculatedgrid();
      reduceSum();
      updateGrid2FromGrid();
      grid.refreshView();
    }, "p_form_equipment_split_d");
  
    // 隐藏 grid2 按钮
    const grid2Toolbar = $NG.getCmpApi("toolbar_p_form_equipment_split_dd");
    ["imp", "addrow", "deleterow", "attachment"].forEach((btn) => grid2Toolbar.hideButton(btn));
  
    useUpdateRows(() => {
      setSpiltAmt();
      reduceSum();
    }, "p_form_equipment_split_dd");
  
    setInterval(() => {
      try {
        const currentLength = grid.getData().length;
        if (currentLength !== dataMaps_key["danjv"]) {
          dataMaps_key["danjv"] = currentLength;
          grid.getData().forEach(sum);
          caculatedgrid();
          console.log("可能发生了单据引用");
        }
      } catch (err) {}
    }, 500);
    /** 监听 grid 数据变化，并同步更新 grid2 */
    function updateGrid2FromGrid() {
      let gridRows = grid.getRows();
      let revenueTypeMap = new Map(gridRows.map((item) => [item.u_revenue_type, item.u_revenue_type_EXName]));
  
      let grid2Rows = grid2.getRows();
      let grid2Types = new Set(grid2Rows.map((item) => item.u_revenue_type));
  
      const _arr = []
      // **新增行**
      revenueTypeMap.forEach((name, type) => {
        if (!grid2Types.has(type)) {
            _arr.push({ u_revenue_type: type, u_revenue_type_EXName: name })
          console.log(`已添加 ${type}（${name}）到 grid2`);
        }
      });
      //改变地址避免影响
      grid2.addRows([..._arr]);
  
      // **删除行**
      grid2Rows.forEach((item) => {
        if (!revenueTypeMap.has(item.u_revenue_type)) {
          grid2.deleteRow(item)
          console.log(`已删除 ${item.u_revenue_type}（${item.u_revenue_type_EXName}）`);
        }
      });
      grid2.refreshView();
    }
  setInterval(()=>{
    console.log(grid2.getRows());
    
  },2000)
    /** 设置切分比例 */
    function setSpiltAmt() {
      grid.getRows().forEach((item) => {
        selectClass(item.u_revenue_type, (data) => {
          if (data) {
            item.u_split_rate = data.u_split_rate;
            sum(item);
            grid.refreshView();
          }
        });
      });
    }
  
    /** 查询切分比例 */
    function selectClass(phid, callback) {
      const result = grid2.getRows().find((item) => item.u_revenue_type == phid) || {};
      console.log("查询切分成功", result);
      callback(result);
    }
  
    // setInterval(() => {
    //   try {
    //     const currentLength = grid.getData().length;
    //     if (currentLength !== dataMaps_key["danjv"]) {
    //       dataMaps_key["danjv"] = currentLength;
    //       grid.getData().forEach(sum);
    //       caculatedgrid();
    //       console.log("可能发生了单据引用");
    //     }
    //   } catch (err) {}
    // }, 500);
  
    /** 计算 grid1 总计金额 */
    function caculatedgrid() {
      let sum_amt_vat = 0,
        sum_amt = 0;
  
      grid.getRows().forEach(({ u_split_amt_vat = 0, u_split_amt = 0 }) => {
        sum_amt_vat += parseFloat(u_split_amt_vat);
        sum_amt += parseFloat(u_split_amt);
      });
  
      $NG.updateState((updater) => {
        updater.data.p_form_equipment_list_split.setProps({ u_split_amt_vat: sum_amt_vat, u_split_amt: sum_amt });
      });
    }
  
    /** 计算每行数据 */
    function sum(item) {
      const taxRate = Number(item.u_tax_rate) || 0;
      const qty = Number(item.u_qty) || 0;
      const oriPrcVat = Number(item.u_ori_prc_vat) || 0;
      const splitRate = Number(item.u_split_rate) || 0;
  
      item.u_ori_prc = oriPrcVat / (1 + taxRate);
      item.u_split_prc_vat = oriPrcVat * splitRate;
      item.u_split_prc = item.u_split_prc_vat / (1 + taxRate);
      item.u_split_amt_vat = qty * item.u_split_prc_vat;
      item.u_split_amt = qty * item.u_split_prc;
      item.u_tax_amt = item.u_split_amt * taxRate;
  
      grid.refreshView();
    }
  
    /** 汇总含税金额 */
    function reduceSum() {
      const summary = grid.getRows().reduce((acc, item) => {
        if (!acc[item.u_revenue_type]) {
          acc[item.u_revenue_type] = { u_split_amt_vat: 0, u_split_amt: 0, u_tax_amt: 0 };
        }
        acc[item.u_revenue_type].u_split_amt_vat += Number(item.u_split_amt_vat) || 0;
        acc[item.u_revenue_type].u_split_amt += Number(item.u_split_amt) || 0;
        acc[item.u_revenue_type].u_tax_amt += Number(item.u_tax_amt) || 0;
        return acc;
      }, {});
  
      grid2.getRows().forEach((item) => {
        const data = summary[item.u_revenue_type] || { u_split_amt_vat: 0, u_split_amt: 0, u_tax_amt: 0 };
        Object.assign(item, data);
      });
  
      console.log(`金额`, summary);
      grid2.refreshView();
    }
  });
  